package com.bill.common.business.dao;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.bill.common.business.dto.BuyQueryDTO;
import com.bill.common.business.entity.Buy;
import com.sinba.common.dao.BaseDAOImplHibernate;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.util.StringUtils;

public class BuyDAO extends BaseDAOImplHibernate<Buy> implements IBuyDAO {

	public PageDTO findBuyPage(BuyQueryDTO queryDTO, String sord, String sidx) {
		// TODO Auto-generated method stub
		final DetachedCriteria dc = DetachedCriteria.forClass(Buy.class);
		
		//买入会员
		if(StringUtils.hasText(queryDTO.getBuyUser())){
			dc.add(Restrictions.eq("buyUser", queryDTO.getBuyUser()));
		}
		
		//状态
		if(queryDTO.getStatus()!=null){
			dc.add(Restrictions.eq("status", queryDTO.getStatus()));
		}
		//多个状态
		if(queryDTO.getMultipleStatus()!=null && queryDTO.getMultipleStatus().length>0){
			dc.add(Restrictions.in("status", queryDTO.getMultipleStatus()));
		}
		
		//未匹配完
		if(queryDTO.isNotEnd()){
			dc.add(Restrictions.gt("dSurplusMoney", 0D));
		}
		
		
		if ( "todaySearch".equals( queryDTO.getSearchType(  ) ) )
        {
            Calendar timeStartCl = new GregorianCalendar(  );
            timeStartCl.setTime( new Date(  ) );
            timeStartCl.set( Calendar.HOUR_OF_DAY, 0 );
            timeStartCl.set( Calendar.MINUTE, 0 );
            timeStartCl.set( Calendar.SECOND, 0 );

            Calendar timeEndCl = new GregorianCalendar(  );
            timeEndCl.setTime( new Date(  ) );
            timeEndCl.set( Calendar.HOUR_OF_DAY, 23 );
            timeEndCl.set( Calendar.MINUTE, 59 );
            timeEndCl.set( Calendar.SECOND, 59 );

            dc.add( Restrictions.between( "createTime",
                                          timeStartCl.getTime(  ),
                                          timeEndCl.getTime(  ) ) );
        }
		
		
		if ( ( queryDTO.getStartTime(  ) != null ) && ( queryDTO.getEndTime(  ) != null ) )
        {
            Calendar endTimeCl = new GregorianCalendar();
            endTimeCl.setTime( queryDTO.getEndTime() );
            endTimeCl.set( Calendar.DATE, endTimeCl.get( Calendar.DATE )+1);
            dc.add( Restrictions.and( Restrictions.le( "createTime", endTimeCl.getTime()),
                                      Restrictions.ge("createTime", queryDTO.getStartTime(  ) ) ) );
        }
		
		if("MatchIng".equals(queryDTO.getSearchType())){
			dc.add(Restrictions.gt("dSurplusMoney", 0D));
			dc.addOrder(Order.desc("status"));
			dc.addOrder(Order.desc("priority"));
			dc.addOrder(Order.asc("createTime"));
		}else{
			if ( ( sord != null ) && ! sord.equals( "" ) && ( sidx != null ) && ! sidx.equals( "" ) )
	        {
	            if ( sord.equals( "desc" ) )
	            {
	                dc.addOrder( Order.desc( sidx ) );
	            } else{
	                dc.addOrder( Order.asc( sidx ) );
	            }
	        }
		}
		
		
		return super.findPageByCriteria( dc,queryDTO.getStart(  ),queryDTO.getLimit(  ) );
	}
	
	
	public List<Buy> findBuy(String buyUser,Integer[] status){
		String hql = "from Buy b where b.buyUser = :buyUser and b.status in (:status)";
		Session session = super.getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query query = session.createQuery(hql);
		query.setParameter("buyUser", buyUser);
		query.setParameterList("status", status);
		return query.list();
	}
	
	public Buy findTop1BuyOrder(){
		Buy buy = null;
		final DetachedCriteria dc = DetachedCriteria.forClass(Buy.class);
		dc.add(Restrictions.in("status",new Integer[]{0,1}));//状态为排队中和匹配成功的
		dc.add(Restrictions.gt("dSurplusMoney", 0D));
/*		dc.createAlias("user", "user");
		dc.add(Restrictions.or(Restrictions.isNull("user.userStatus"), Restrictions.eq("user.userStatus", "0")));*/
		dc.addOrder(Order.desc("status"));
		dc.addOrder(Order.desc("priority"));
		dc.addOrder(Order.asc("createTime"));
		PageDTO pageDTO = super.findPageByCriteria( dc,0,1);
		if(pageDTO.getTotalSize()>0){
			buy = (Buy)pageDTO.getData().get(0);
		}
		return buy;
	} 
	
	
	/**
	 * 查出可分红数据
	 * 排除7天
	 * @return
	 */
	public List<Buy> findFengHongData(){
		String hql = "from Buy where to_days(now())-to_days(createTime)<=7 and fengHongDays<7 and status not in (3)";
		return super.getHibernateTemplate().find(hql);
	}

	
	/**
	 * 当天的所有买入
	 * @return
	 */
	public List<Object> todayAllBuy(){
		String hql = "select sum(dBuyMoney) as allBuy from Buy where year(matchTime)=year(now()) and month(matchTime)=month(now()) and day(matchTime)=day(now())";
		return super.getHibernateTemplate().find(hql);
	}
	
	/**
	 * 未完成的所有买入
	 * @return
	 */
	public List<Object> undoneAllBuy(){
		String hql = "select sum(dSurplusMoney) as totals from Buy where status in (0,1)";
		return super.getHibernateTemplate().find(hql);
	}

}
